import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:kq_flutter_core_widget/utils/log.dart';

/// 导航调用原生工具类
class NavigateNativeUtil {
  static const _methodChannelName = 'flutter.keqiang.com/navigation';

  static const _platformMethod = MethodChannel(_methodChannelName);

  /// 退出当前原生页面
  ///
  /// 注意：Android端的FlutterActivity 必须实现[IKqRoute]
  static closeNativePage() async {
    // var cur = Get.currentRoute;
    // if (cur.contains('fromNative')) {
    //   try {
    //     await _platformMethod.invokeMethod('close');
    //   } on PlatformException catch (e) {
    //     debugPrint(e.message);
    //   }
    // } else{
    //   Get.back();
    // }

    if (Get.global(null).currentState?.canPop() == false) {
      try {
        await _platformMethod.invokeMethod('close');
      } on PlatformException catch (e) {
        debugPrint(e.message);
      }
    } else {
      Get.back();
    }
  }

  /// 打开原生页面
  ///
  /// 注意：Android端的FlutterActivity 必须实现[IKqRoute]
  static openNativePage(String pageName,
      {Map<String, dynamic>? params, Function(dynamic result)? callback}) {
    try {
      _platformMethod.invokeMethod(
        'open',
        {'pageName': pageName, 'params': params},
      ).then(
        (value) => {
          callback?.call(value)
        },
      );
    } on PlatformException catch (e) {
      debugPrint(e.message);
      callback?.call(null);
    }
  }

  /// 退出登录
  static exitLogin() async {
    try {
      await _platformMethod.invokeMethod('exitLogin');
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
  }

  /// 设置横竖屏切换逻辑
  /// [OrientationMode.portrait] :强制竖屏
  /// [OrientationMode.landscape] :强制横屏
  /// [OrientationMode.auto] :自动旋转
  static setOrientationMode(OrientationMode orientationMode) async {
    try {
      await _platformMethod.invokeMethod(
          'setOrientationMode', {'orientationMode': orientationMode.code});
    } on PlatformException catch (e) {
      debugPrint(e.message);
    }
  }
}

enum OrientationMode {
  ///竖屏
  portrait(0),

  ///横屏
  landscape(1),

  ///自动旋转
  auto(2);

  final int code;

  const OrientationMode(this.code);
}
